package com.grain.mall.goods.mq;

import base.MqBaseModel;
import cn.hutool.core.util.IdUtil;
import myConst.MQConst;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class Producer {

    public static void main(String[] args) throws Exception {
        MQConst.MQEnum mqEnum = MQConst.MQEnum.GOODS_ORDER_CREATE_LIST;
        // 初始化一个producer并设置Producer group name
        DefaultMQProducer producer = new DefaultMQProducer(mqEnum.getProducerGroup()); //（1）
        // 设置NameServer地址
        producer.setNamesrvAddr("192.168.171.129:9876");  //（2）
        // 启动producer
        producer.start();
        for (int i = 0; i < 3; i++) {
            // 创建一条消息，并指定topic、tag、body等信息，tag可以理解成标签，对消息进行再归类，RocketMQ可以在消费端对tag进行过滤
//            Message msg = new Message(mqEnum.getTopic()/* Topic */,
//                    "TagA" /* Tag */,
//                    ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
            MqBaseModel mqBaseModel = initMqBaseModel(i);
            Message message = new Message(mqEnum.getTopic(),  mqBaseModel.toJsonString().getBytes(RemotingHelper.DEFAULT_CHARSET));   //（3）
            Message message2 = new Message(mqEnum.getTopic(),  mqBaseModel.toJsonString().getBytes(RemotingHelper.DEFAULT_CHARSET));   //（3）
            // 测试延迟消息
//            message.setDelayTimeLevel(3);
            // 利用producer进行发送，并同步等待发送结果
//            SendResult sendResult = producer.send(message);   //（4）
            // 批量发 使用集合
            List<Message> messages = Arrays.asList(message, message2);
            SendResult sendResult = producer.send(messages);
            System.out.printf("%s%n", sendResult);
        }
        // 一旦producer不再使用，关闭producer
        producer.shutdown();
    }

    public static MqBaseModel initMqBaseModel(int i) {
        MqBaseModel<String> mqBaseModel = new MqBaseModel<>();
        String key = IdUtil.fastSimpleUUID();
        mqBaseModel.setKey(key);
        mqBaseModel.setSource("mall-goods");
        mqBaseModel.setMessageBody("hello consumer ====== " + i);
        return mqBaseModel;
    }

}
